<?php

namespace app\api\model;

use think\Cache;
use think\Model;

class Area extends Model
{
    protected $visible = ['id', 'name', 'pid'];

    public static function getAll()
    {
        $areas = json_decode(Cache::get('areas'), true);
        if (!$areas) {
            $areas = self::all();
            Cache::set('areas', json_encode($areas), 0);
        }
        return $areas;
    }

    /**
     * 省市区
     */
    public static function getAreas()
    {
        $areas = self::getAll();
        return self::getTree($areas);
    }

    /**
     * 无限级
     */
    public static function getTree($data, $pid = 0)
    {
        $arr = [];
        foreach ($data as $key=>$val) {
            if ($val['pid'] == $pid) {
                $val['childs'] = self::getTree($data, $val['id']);
                $arr[] = $val;
                unset($data[$key]);
            }
        }
        return $arr;
    }

    /**
     * 城市
     * A ~ Z排序
     */
    public static function city()
    {
        $city = json_decode(Cache::get('city_a_z'), true);
        if (!$city) {
            $city = self::where('level', 2)->order('first asc')->select();
            Cache::set('city_a_z', json_encode($city), 0);
        }
        return $city;
    }

    /**
     * 获取城市
     */
    public static function getCity()
    {
        $city = self::city();
        if (!$city) {
            BaseModel::error(11000);
        }
        $first = array_unique(array_column($city, 'first'));
        $data = [];
        foreach ($first as $val) {
            foreach ($city as $v) {
                if ($v['first'] == $val) {
                    $data[$val][] = $v;
                }
            }
        }
        return $data;
    }


}
